<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>Upgrade your database</title>
	</head>
	<body>
<?php

require_once(dirname(__FILE__) . '/../config.php');
require_once(APPLICATION_ROOT . '/db.php');

$admin_password = filter_input(INPUT_COOKIE, 'admin_password', FILTER_SANITIZE_STRING);

if ($admin_password != BSDDS_ADMIN_PASSWORD_HASHED) {
	die("Invalid password");
}

$this_page = filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_URL);

if (!$_POST) {
?>
		<h1>Upgrade your database</h1>

		<form action = "<?php echo $this_page; ?>" method="POST">
			<input type="submit" name="submit"
			 style="font-size: 30px; padding: 10px;" value="Upgrade">
		</form>
<?php
} else {

	# For v0.20 - check if transaction_time and time are datetime.
	$result = mysql_query("SELECT transaction_time, time FROM " . BSDDS_PURCHASE_TABLE . " LIMIT 1");
	$fields = mysql_num_fields($result);

	if ((mysql_field_type($result, 0) == "int") AND (mysql_field_type($result, 0) == "int")) {

		$upgrade_queries[] = 'ALTER TABLE ' . BSDDS_PURCHASE_TABLE . ' ADD COLUMN transaction_time_new DATETIME AFTER transaction_time';
		$upgrade_queries[] = 'ALTER TABLE ' . BSDDS_PURCHASE_TABLE . ' ADD COLUMN time_new DATETIME AFTER time;';
		$upgrade_queries[] = 'UPDATE ' . BSDDS_PURCHASE_TABLE . ' SET transaction_time_new = FROM_UNIXTIME(transaction_time);';
		$upgrade_queries[] = 'UPDATE ' . BSDDS_PURCHASE_TABLE . ' SET time_new = FROM_UNIXTIME(time);';
		$upgrade_queries[] = 'ALTER TABLE ' . BSDDS_PURCHASE_TABLE . ' DROP COLUMN transaction_time;';
		$upgrade_queries[] = 'ALTER TABLE ' . BSDDS_PURCHASE_TABLE . ' DROP COLUMN time;';
		$upgrade_queries[] = 'ALTER TABLE ' . BSDDS_PURCHASE_TABLE . ' CHANGE transaction_time_new transaction_time DATETIME;';
		$upgrade_queries[] = 'ALTER TABLE ' . BSDDS_PURCHASE_TABLE . ' CHANGE time_new time DATETIME;';

		foreach ($upgrade_queries as $sql) {
			echo $sql . "<br />";
			mysql_query($sql) or die(mysql_error());
		}

		$upgraded = TRUE;

	}

	if ($upgraded == TRUE) {
		echo "		<p>Database upgraded successfully.</p>";
	} else {
		echo "		<p>No upgrade required.</p>";
	}
}
?>
	</body>
</html>